#!/usr/bin/perl
## Nicholas' PCAP to Ascii Parsing Script - April 7, 2013.
# CONFIG: Change to your snort directory/file structure - example: /var/log/snort/tcpdump.pcap.*
my @FileLst = </tmp/pcap/tcpdump*>; 

# Don't Touch:
use Net::Pcap; use NetPacket::Ethernet qw(:ALL); use NetPacket::IP; use NetPacket::TCP;
use File::Basename;

sort @FileLst; my $File = pop (@FileLst);
my $Output = dirname($File) . "/ascii-" . basename($File) . ".txt";
open ($OutF, ">$Output"); # || chomp $!; die "Unable to open output file: $Output ($!)\n";
our ($myfilename, $mydir, $myext) = fileparse($File, qr/[^.]*/);
my $PacketNum = 1; $| = 1;
my $pcap = Net::Pcap::open_offline("$File", \$STDOUT) || die "\n***:failed to open $File\n";
           Net::Pcap::loop($pcap, -1, \&ProcPckt, '');

sub ProcPckt {
	my ($user, $hdr, $pkt) = @_;
        $ip_header = NetPacket::IP->decode(eth_strip($pkt));
        $tcp_header = NetPacket::TCP->decode($ip_header->{data}); ## Decodes TCP/UDP/ICMP just fine.
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime("$hdr->{tv_sec}"); 
	$mon++; if ($mon =~ /^[1-9]$/) { $mon = "0$mon"; }
	if ($mday =~ /^[1-9]$/) { $mday = "0$mday"; } if ($hour =~ /^[1-9]$/) { $hour = "0$hour"; }
	if ($min =~ /^[1-9]$/) { $min = "0$min"; } if ($sec =~ /^[1-9]$/) { $sec = "0$sec"; }
	print $OutF "[**] [$myext" . "::" . $PacketNum . "::$hdr->{tv_sec}] PCAP to Ascii Output [**]\n"; 
	print $OutF "$mon/$mday-$hour:$min:$sec $ip_header->{src_ip}:$tcp_header->{src_port} -> ";
	print $OutF "$ip_header->{dest_ip}:$tcp_header->{dest_port}\n";
	if ($tcp_header->{data}) { 
		print $OutF "Payload:\n";
		my $buf = $tcp_header->{data}; $buf =~ s/\x00\x00\x00/ /gi; $buf =~ s/([^\x00])\x00([^\x00])/$1$2/g; $buf =~ s/[^([:print:]|\r|\n)]/./g;
		print $OutF "$buf\n\n";  
	}
	else { print $OutF "\t[NO PRINTABLE PAYLOAD]\n\n"; }
	$PacketNum++;
}

close ($OutF); 
